package cn.itcast.hotel.constants;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.itcast.hotel.pojo.EventNotificationAlert;
import cn.itcast.hotel.pojo.VisitorStatistics;
import cn.itcast.hotel.pojo.VisitorTotalVo;
import cn.itcast.hotel.pojo.bo.VisitorTotalBo;
import cn.itcast.hotel.util.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@RestController()
@Slf4j
public class TestController {

    /**
     * 今日入馆人数
     */
    private int todayEntries;

    /**
     * 实时馆内人数
     */
    private int realTimeEntries;


    @PostMapping("/importData")
    @CrossOrigin(origins = "*")
    public void receiveXmlData(@RequestBody String xml) throws IOException {
        log.info("xml:{}", xml);
        // 将xml 变成文件流
        InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
        parseXmlToStatistics(inputStream);
    }
    private void parseXmlToStatistics(InputStream xmlData) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(EventNotificationAlert.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            SAXParserFactory sax = SAXParserFactory.newInstance();
            sax.setNamespaceAware(false);
            XMLReader xmlReader = sax.newSAXParser().getXMLReader();
            Source source = new SAXSource(xmlReader, new InputSource(xmlData));
            EventNotificationAlert alert = (EventNotificationAlert) unmarshaller.unmarshal(source);
            //EventNotificationAlert alert = (EventNotificationAlert) unmarshaller.unmarshal(new StringReader(xmlData));
            int totalEntries = 0;
            if(alert.getEventType().contains("PeopleCounting")){
                if(alert.getPeopleCounting().getStatisticalMethods().equals("realTime")){
                    // 解析D:\count.json文件中的数据
                    String directoryPath = "D:\\total";
                    String initFile = "D:\\total\\count.json";
                    // 以今天的日期命名的json文件输出到D:\total文件夹下，20240928.json如果有则删除重新建立文件
                    // 获取今天的日期
                    LocalDate today = LocalDate.now();
                    // 格式化日期为yyyyMMdd格式
                    String formattedDate = today.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
                    String fileName = formattedDate+"_"+alert.getIpAddress() + ".json";
                    // 判断directoryPath是否存在，不存在则创建
                    File directory = new File(directoryPath);
                    if (!directory.exists()) {
                        directory.mkdir();
                    }
                    String initFilePath = initFile;
                    if (!Files.exists(Paths.get(initFilePath))) {
                        File initFile1 = new File(initFilePath);
                        initFile1.createNewFile();
                        // 构建JSON内容
                        String jsonContent = "{"
                                +"\"todayEntries\":0," +
                                "\"realTimeEntries\":0," +
                                "\"totalEntries\":10000" +
                                "}";
                        // 写入文件
                        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(initFilePath))) {
                            writer.write(jsonContent);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    Path filePath = Paths.get(directoryPath, fileName);
                    int totalEntries1 = 0;
                    try {
                        // 检查文件是否存在
                        if (Files.exists(filePath)) {
                            String jsonContent1 = new String(Files.readAllBytes(Paths.get(directoryPath+"\\"+fileName)));
                            JSONObject jsonObject = JSONObject.parseObject(jsonContent1);
                            totalEntries1 = Integer.valueOf(jsonObject.getInteger("totalEntries"));
                            // 如果文件存在，则删除
                            Files.delete(filePath);
                        }
                        // 创建新的文件
                        Files.createFile(filePath);
                    } catch (IOException e) {
                        // 处理异常
                        e.printStackTrace();
                    }
                    // 从解析后的对象中提取数据
//                    if (alert.getPeopleCounting() != null) {
//                        int enter = alert.getPeopleCounting().getEnter();
//                        int exit = alert.getPeopleCounting().getExit();
//                        if (enter - exit < 0) {
//                            realTimeEntries = 0;
//                        }else {
//                            realTimeEntries = enter - exit;
//                        }
//                        todayEntries = enter;
//                    }
                    String jsonContent = null;
                    int enter = alert.getPeopleCounting().getEnter();
                    int exit = alert.getPeopleCounting().getExit();
                    if(alert.getPeopleCounting().getEnter() == 0 && alert.getPeopleCounting().getExit() == 0){
                        jsonContent = "{"
                                +"\"todayEntries\":0," +
                                "\"realTimeEntries\":0," +
                                "\"totalEntries\":"+ totalEntries1 +
                                "}";
                    }else {
                        int realTimeEntriesTemp = enter - exit <0 ? 0 : enter - exit;
                        // 写入文件
                        // 构建JSON内容
                        jsonContent = "{"
                                +"\"todayEntries\":"+ enter +","+
                                "\"realTimeEntries\":"+realTimeEntriesTemp + ","+
                                "\"totalEntries\":"+enter +
                                "}";
                    }
                    // 写入文件
                    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(directoryPath, fileName))) {
                        writer.write(jsonContent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/getData")
    @CrossOrigin(origins = "*")
    public ResponseEntity<VisitorStatistics> getData() throws IOException {
        int totalEntries = 0;
        int todayEntries = 0;
        int realTimeEntries = 0;
        // 解析D:\count.json文件中的数据
        String directoryPath = "D:\\total";
        File directory = new File(directoryPath);
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        String jsonContent = new String(Files.readAllBytes(Paths.get(directoryPath+"\\"+file.getName())));
                        JSONObject jsonObject = JSONObject.parseObject(jsonContent);
                        totalEntries += Integer.valueOf(jsonObject.getInteger("totalEntries"));
                        todayEntries += Integer.valueOf(jsonObject.getInteger("todayEntries"));
                        realTimeEntries += Integer.valueOf(jsonObject.getInteger("realTimeEntries"));
                    }
                }
            }
        }
        VisitorStatistics visitorStatistics = new VisitorStatistics(todayEntries, realTimeEntries, totalEntries);
        return ResponseEntity.ok(visitorStatistics);
    }

    /**
     * 导出历史数据
     */
    @GetMapping("/exportData")
    @CrossOrigin(origins = "*")
    public void exportData(VisitorTotalBo visitorTotalBo, HttpServletResponse response) throws IOException {
        LinkedList<VisitorTotalVo> visitorTotalVos = queryData(visitorTotalBo);
        ExcelUtil.exportExcel(visitorTotalVos,"合计", VisitorTotalVo.class,  response);
    }

    /**
     * 查询历史数据
     */
    @GetMapping("/queryData")
    @CrossOrigin(origins = "*")
    public LinkedList<VisitorTotalVo> queryData(VisitorTotalBo visitorTotalBo) throws IOException {
        DateTime startDate = DateUtil.parse(visitorTotalBo.getStartDate(), "yyyy-MM-dd");
        DateTime endDate = DateUtil.parse(visitorTotalBo.getEndDate(), "yyyy-MM-dd");
        List<DateTime> dateList = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
        LinkedList<VisitorTotalVo> visitorTotalVos = new LinkedList<>();
        for (DateTime date : dateList) {
            String dateStr = DateUtil.format(date, "yyyy-MM-dd");
            VisitorTotalVo visitorTotalVo = new VisitorTotalVo();
            visitorTotalVo.setQueryDate(dateStr);
            int todayEntries = 0;
            int totalEntries = 0;
            // 解析D:\count.json文件中的数据
            String directoryPath = "D:\\total";
            File directory = new File(directoryPath);
            if (directory.exists() && directory.isDirectory()) {
                File[] files = directory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            if ("count.json".equals(file.getName())) {
                                String jsonContent = new String(Files.readAllBytes(Paths.get(directoryPath+"\\"+file.getName())));
                                JSONObject jsonObject = JSONObject.parseObject(jsonContent);
                                totalEntries += Integer.valueOf(jsonObject.getInteger("totalEntries"));
                            }else {
                                String fileDateStr = file.getName().split("_")[0];
                                DateTime fileDate = DateUtil.parse(fileDateStr, "yyyy-MM-dd");
                                if(fileDate.isBeforeOrEquals(date)) {
                                    String jsonContent = new String(Files.readAllBytes(Paths.get(directoryPath+"\\"+file.getName())));
                                    JSONObject jsonObject = JSONObject.parseObject(jsonContent);
                                    totalEntries += Integer.valueOf(jsonObject.getInteger("totalEntries"));
                                    todayEntries += Integer.valueOf(jsonObject.getInteger("todayEntries"));
                                }
                            }
                        }
                    }
                }
            }
            visitorTotalVo.setTotalEntries(totalEntries);
            visitorTotalVo.setTodayEntries(todayEntries);
            visitorTotalVos.add(visitorTotalVo);
            return visitorTotalVos;
        }
        return visitorTotalVos;

    }

}

